<?php
class ModelArticleArticle extends Model {

	public function addArticle($data) {
		global $V5_NOW;
		$data['date_added'] = $V5_NOW;
		$data['date_modified'] = $V5_NOW;
		$article_id = $this->db->insert('article', $data);
		
		$content_data = array('content' => $data['content']);
		$content_data['article_id'] = $article_id;
		$this->db->insert('article_content', $content_data);

		return $article_id;
	}

	public function editArticle($article_id, $data) {
		global $V5_NOW;
		$data['date_modified'] = $V5_NOW;
		$this->db->update('article', $data, "article_id = $article_id");

		$content_data = array('content' => $data['content']);
		return $this->db->update('article_content', $content_data, "article_id = $article_id");
	}

	public function getArticle($article_id) {
		return $this->db->queryOne("SELECT a.*, ac.content FROM @@article a LEFT JOIN @@article_content ac
				ON a.article_id = ac.article_id WHERE a.article_id = $article_id");
	}

	public function deleteArticle($article_id) {
		if (is_array($article_id)) $article_id = implode(',', $article_id);
		$this->db->runSql("DELETE FROM @@article_content WHERE article_id IN ($article_id)");
		$this->db->runSql("DELETE FROM @@article WHERE article_id IN ($article_id)");
	}

	public function getArticles($filter = null) {
		$sql = "SELECT * FROM @@article WHERE 1";
		if ($filter) {
			if ($filter->get('filter_category_id')) {
				$sql .= " AND category_id = " . (int) $filter->get('filter_category_id');
			}
			$sql .= $filter->sort('article_id', 'DESC');
			$sql .= $filter->limit();
		}

		$query = $this->db->query($sql);
		return $query->rows;
	}

	public function getTotalArticles($filter = null) {
		$sql = "SELECT COUNT(*) AS total FROM @@article WHERE 1";
		if ($filter) {
			if ($filter->get('category_id')) {
				$sql .= " AND category_id = " . (int) $filter->get('category_id');
			}
		}
		return $this->db->queryOne($sql);
	}

	public function getTotalArticlesByCategoryId($category_id) {
		$sql = "SELECT COUNT(*) AS total FROM @@article WHERE category_id = $category_id";
		return $this->db->queryOne($sql);
	}
	
	/** category **/

	public function addCategory($data) {
		return $this->db->insert('article_category', $data);
	}

	public function editCategory($category_id, $data) {
		return $this->db->update('article_category', $data, "category_id = $category_id");
	}

	public function deleteCategory($category_id) {
		if (is_array($category_id)) $category_id = implode(',', $category_id);
		$this->db->runSql("DELETE FROM @@article_category WHERE category_id IN ($category_id)");
	}

	public function getCategory($category_id) {
		return $this->db->queryOne("SELECT * FROM @@article_category WHERE category_id = $category_id");
	}

	public function getCategories() {
		$query = $this->db->query("SELECT * FROM @@article_category ORDER BY sort_order");
		return $query->rows;
	}
}